<?php
require_once('DataObject/DomainModel.php');
//$translation = Translator::loadTranslation('en_EN', 'common');
//$this->template->set('stronaGlowna', $tlumaczenieSG);

class TranslatorModule extends DomainModel {
	protected $moduleName;
	protected $fileName;
	protected $dictionary;
	protected $dir;

	public function __construct($directory, $fileName){
		$this->moduleName = substr($fileName, 0, strpos($fileName, '.php'));
		$this->fileName = $fileName;
		$this->dictionary = require($directory.$fileName);
		$this->dir = str_replace($_SERVER['DOCUMENT_ROOT'],'',$directory);
	}
	
	public function t($key){
		if(array_key_exists($key, $this->dictionary)){
			if (empty($this->dictionary[$key]))
				return "$key";
				//return "[not translated] |".$this->dir."".$this->moduleName."| $key";
			else
				return $this->dictionary[$key];
		}
		
		else 
			return "$key";
			//return "[not translated] |".$this->dir."".$this->moduleName."| $key";
	}
	
	public function translate($key){
		return $this->t($key);
	}
	
	public static function update($file, $data = array()){
		ob_start();
		echo "<?php return array( \n";
			$i = 1;
			foreach ($data as $key => $value){
				echo "\t".'"'.$key.'" => "'.$value.'"';
				if($i < sizeof($data))
					echo ',';
				echo "\n";
				$i++;
			}
			
		
		echo '); ?>';
		$content = ob_get_contents();
	    ob_end_clean();
	    
	    file_put_contents($file, $content);
	}
	 
}

class Translator extends DomainModel 
{
	protected $shortcut;
	protected $modules;
	
	public function __construct($shortcut = 'default'){
		$this->shortcut = $shortcut;
	}
	
	public function loadModules($path){
		if(!is_dir($_SERVER['DOCUMENT_ROOT'].$path.$this->shortcut))
			throw new Exception('Directory does not exists!');
			
		$dir = opendir($_SERVER['DOCUMENT_ROOT'].$path.$this->shortcut);
		
		while (false !== ($file = readdir($dir))) {
	        if(strpos($file, '.php') > 0){
	        	$this->modules[] = new TranslatorModule($_SERVER['DOCUMENT_ROOT'].$path.$this->shortcut, $file);
	        }
	    }		
	}
	
	public static function loadTranslation($currentLang = 'default', $moduleName, $path = '/application/locale/'){
		$fileName = $moduleName.'.php';
		if(file_exists($_SERVER['DOCUMENT_ROOT'].$path.$currentLang.'/'.$fileName)){
			return new TranslatorModule($_SERVER['DOCUMENT_ROOT'].$path.$currentLang.'/', $fileName);
		}else{
			return new TranslatorModule($_SERVER['DOCUMENT_ROOT'].$path.'default/', $fileName);
		}
	}
	
	public static function loadCookie($moduleName){
		$currentLang = $_COOKIE['lang'];
		$fileName = $moduleName.'.php';
		if(file_exists($_SERVER['DOCUMENT_ROOT'].$path.$currentLang.'/'.$fileName)){
			return new TranslatorModule($_SERVER['DOCUMENT_ROOT'].$path.$currentLang.'/', $fileName);
		}else{
			return new TranslatorModule($_SERVER['DOCUMENT_ROOT'].$path.'default/', $fileName);
		}
	}
}


?>